package com.lagou.rpc.consumer;

import com.lagou.rpc.consumer.client.RpcClientManger;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.List;

@SpringBootApplication
@EnableScheduling
public class ClientBootstrapApplication implements DisposableBean {

    @Autowired
    private RpcClientManger rpcClientManager;

    @Autowired
    private CuratorFramework curatorFramework;

    public static void main(String[] args) {
        SpringApplication.run(ClientBootstrapApplication.class, args);
    }

    @Override
    public void destroy() throws Exception {
        rpcClientManager.close();
    }


    @Scheduled(initialDelay = 10000,fixedDelay = 5000)
    public void scheduled() throws Exception {
        String path = "/client/" + getRealIp();
        List<String> nodes = curatorFramework.getChildren().forPath(path);
        for (String node : nodes) {
            byte[] bytes = curatorFramework.getData().forPath(path+"/"+node);
            String str = new String(bytes, Charset.forName("UTF-8"));
            long lastResponseTime = Long.valueOf(str.split(":")[1]);
            if(lastResponseTime == 0 || System.currentTimeMillis() - lastResponseTime < 5000){
                continue;
            }else {
                System.out.println("reponse time out");
                curatorFramework.setData().forPath(path+"/"+node,"0:0".getBytes(StandardCharsets.UTF_8));
            }
        }
    }

    public String getRealIp() throws SocketException {
        String localip = null;// 本地IP，如果没有配置外网IP则返回它
        String netip = null;// 外网IP
        Enumeration<NetworkInterface> netInterfaces =
                NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if (!ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else if (ip.isSiteLocalAddress()
                        && !ip.isLoopbackAddress()
                        && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                    localip = ip.getHostAddress();
                }
            }
        }
        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }
}
